#!/bin/bash

# 定义一个函数来执行命令并检查错误
execute_with_check() {
    "$@"  # 执行传递进来的命令
    if [ $? -ne 0 ]; then
        echo "命令执行失败: $*"
        exit 1
    fi
}

check_and_copy() {
    local source_dir="$1"
    local target_dir="$2"
    local dir_name="$3"
    # 检查目标目录是否存在
    if [ ! -d "$target_dir/$dir_name" ]; then
        execute_with_check cp -r "$source_dir" "$target_dir"
    else
        echo "目录 '$target_dir/$dir_name' 已存在，跳过复制。"
    fi
}
 

#删除源码，复制install文件安装

#删除LC,重新复制LC
execute_with_check cd /home/firefly
execute_with_check sudo rm -rf LC
# execute_with_check mkdir /home/firefly/LC
# execute_with_check cd /home/firefly/LC

execute_with_check cp -r '/media/firefly/新加卷/核心板刷机/LC' /home/firefly

#使用install文件无需编译
# execute_with_check cd /home/firefly/LC
# execute_with_check source /opt/ros/noetic/setup.sh

# execute_with_check catkin_make -DCATKIN_WHITELIST_PACKAGES="custom_msgs"
# execute_with_check catkin_make -DCATKIN_WHITELIST_PACKAGES="hipnuc_imu"
# execute_with_check catkin_make -DCATKIN_WHITELIST_PACKAGES=""

# 定义要写入的内容
CONTENT="[Unit]
Description=/etc/rc.local Compatibility 
ConditionPathExists=/etc/rc.local 
 
[Service]
Type=forking 
ExecStart=/etc/rc.local start 
TimeoutSec=0 
StandardOutput=tty 
RemainAfterExit=yes 
SysVStartPriority=99 
 
[Install]
WantedBy=multi-user.target
"
# 使用echo和重定向写入内容
execute_with_check echo "$CONTENT" | sudo tee /etc/systemd/system/rc-local.service > /dev/null

# 定义要写入的内容
CONTENT1="#! /bin/bash

source /opt/ros/noetic/setup.bash
cd /home/firefly/LC
read -r root_dir < /home/firefly/LC/config/soft_version
cd \$root_dir
source install/setup.bash
roslaunch mowing_robot mowing_robot.launch &
"
# 使用echo和重定向写入内容
execute_with_check echo "$CONTENT1" | sudo tee /etc/rc.local > /dev/null

execute_with_check sudo chmod 777 /etc/rc.local
execute_with_check sudo systemctl enable rc-local.service
execute_with_check sudo systemctl start rc-local.service


# 定义要修改的文件路径
launch_file_path="/opt/ros/noetic/share/nmea_navsat_driver/launch/nmea_serial_driver.launch"
# 使用sed命令替换port的默认值
sudo sed -i 's/<arg name="port" default="\/dev\/ttyUSB0" \/>/<arg name="port" default="\/dev\/ttyS3" \/>/g' "$launch_file_path"
# 使用sed命令替换baud的默认值
sudo sed -i 's/<arg name="baud" default="[0-9]\+" \/>/<arg name="baud" default="9600" \/>/g' "$launch_file_path"
sudo cat "$launch_file_path"
echo "nmea_serial_driver.launch 文件已成功修改。"

# 脚本结束
echo "全部安装成功，请手动配置蓝牙"
sudo cutecom
# sudo reboot